package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.FollowRelation;
import cn.wolfcode.trip.base.mapper.FollowRelationMapper;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IFollowRelationService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class FollowRelationServiceImpl implements IFollowRelationService {
    @Autowired
    private FollowRelationMapper followRelationMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public void addFriend(FollowRelation entity, String action) {
        /*关注*/
        if ("addFriend".equals(action)) {
            /*查询是否已关注*/
            if (!isFan(entity.getUserId(),entity.getFollowedId())) {
                /*设置关注时间*/
                entity.setFollowedTime(new Date());
                followRelationMapper.insert(entity);
                /*设置user表中登陆用户关注数+1*/
                userMapper.updateCountUp(entity.getFollowedId(), null, 1);
                /*设置user表中用户粉丝数+1*/
                userMapper.updateCountUp(entity.getUserId(), 1, null);
            }

        }
        /*取消关注*/
        else if ("delFriend".equals(action)) {
            /*删除关注表中数据*/
            followRelationMapper.deleteByBothId(entity.getUserId(),entity.getFollowedId());
            /*设置user表中登陆用户关注数-1*/
            userMapper.updateCountDown(entity.getFollowedId(),null,1);
            /*设置user表中用户粉丝数-1*/
            userMapper.updateCountDown(entity.getUserId(),1,null);
        } else {
            throw new RuntimeException("关注状态异常!");
        }
    }

    @Override
    public boolean isFan(Long userId, Long followedId) {
        int count = followRelationMapper.selectIsFan(userId, followedId);
        if(count!=0){
            return true;
        }
        return false;
    }

    @Override
    public PageInfo query(QueryObject queryObject) {
        followRelationMapper.selectForList(queryObject);
        return null;
    }
}
